//microcommand define vits
signature("<model> <text:rawtext>")
async function getModels() {
  try {
    return Object.keys(await ctx.get("console.services.luna_vits_data").getSpeakerKeyMap()).filter(k => k.endsWith("_AUTO")).map(k => k.slice(0, -5)).sort(new Intl.Collator("zh-CN", { collation: "stroke", numeric: true }).compare)
  } catch (e) {
    ctx.logger.warn(e)
  }
}
function getMaxLength() {
  return ctx.registry._internal.get(require("koishi-plugin-luna-vits").apply)?.config.maxLength ?? 100
}
option("list", "--models", { notUsage: true })
option("file", "-f")
option("truncate", "-t")
example("vits lnn 你好，我是纯真灵魂")
before(async ({ session, options, args }) => {
  if (options.help || options.list) return
  if (!args.length) return session.execute({ name: "help", args: [name] })
  if (args.length < 2) return session.i18n("internal.insufficient-arguments")
})
action(async ({ session, options }, model, text) => {
  const models = await getModels()
  if (options.list) {
    return models && h("message", { forward: true }, session.text(".models", [models.join(session.text("general.comma"))]))
  }
  const maxLength = getMaxLength()
  if (options.truncate) text = text.slice(0, maxLength - (text.codePointAt(maxLength - 1) > 0xffff))
  else if (text.length > maxLength) return session.i18n(".too-long", [maxLength])
  if (!models?.includes(model)) return session.i18n(".model-not-found")
  const result = await session.execute({
    name: "lunavits",
    args: [text],
    options: { speaker: model },
  }, true)
  if (options.file) return h.transform(result, { audio: attrs => h.file(attrs.src.replace(/^data:wav;/, "data:audio/wav;")) })
  return h.transform(result, { audio: attrs => h.audio(attrs.src.replace(/^data:wav;/, "data:audio/wav;")) })
  return result
})
locale("zh-CN", {
  description: "语音合成",
  arguments: { model: "语音模型名称", text: "文本" },
  options: { list: "显示可用的语音模型列表", file: "以文件形式输出", truncate: "截断过长的输入" },
  usage: "本指令为“lunavits -s &lt;model&gt;_AUTO &lt;text...&gt;”的语法糖。",
  messages: {
    "models": "当前可用的语音模型有：{0}",
    "model-not-found": "语音模型不存在…",
    "too-long": "输入长度不能超过 {0}…",
  },
})